package com.cl.blog.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author 付
 * @Date 2024-03-23 17:29
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Component
@Slf4j
public class RedisMessageListener implements MessageListener {

	@Resource
	StringRedisTemplate stringRedisTemplate;
	@Resource
	ObjectMapper objectMapper;


	private Session session;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		log.info("监听的消息--->"+message);
		// 获取消息
		byte[] messageBody = message.getBody();

		String messageContent = new String(message.getBody(), StandardCharsets.UTF_8);

		System.out.println("处理的消息--->" + messageContent);
		// 获取监听的频道
		byte[] channelByte = message.getChannel();
		String channel = new String(message.getChannel(), StandardCharsets.UTF_8);

		// 使用字符串序列化器转换
		// 渠道名称转换
		String patternStr = new String(pattern);
		System.out.println("---频道---: " + channel);

		if(session!=null && session.isOpen()){
			System.out.println("会话对象："+session);
			try {
				session.getBasicRemote().sendText("发送了一条消息");
			} catch (IOException e) {
				log.error("出现异常了------>"+e);
				throw new RuntimeException(e);
			}
		}
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

}                   

